/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import ejb.BusinessLogicLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Marco
 */
public class ServletRegistrazione extends HttpServlet {
    @EJB
    private BusinessLogicLocal businessLogic;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        HttpSession session = request.getSession();

        
        String nome = request.getParameter("nome");
        String cognome = request.getParameter("cognome");
        String codiceFiscale = request.getParameter("codicefiscale");
        String sesso = request.getParameter("sesso");
        String giornoNascita = request.getParameter("giornonascita");
        String meseNascita = request.getParameter("mesenascita");
        String annoNascita = request.getParameter("annonascita");
        String luogoNascita = request.getParameter("luogonascita");
        String indirizzoResidenza = request.getParameter("indirizzo");
        String email = request.getParameter("email");
        String password = request.getParameter("password1");
        String confPassword = request.getParameter("password2");
        String telefono = request.getParameter("telefono");
        //PrintWriter out = response.getWriter();
        boolean insert = true;
        
        if(nome.equals("")){
            System.out.println("nome");
            insert=false;
        }
        else if(cognome.equals("")){
            System.out.println("cognome");
            insert=false;
        }
        else if(codiceFiscale.equals("")){
            System.out.println("CF");
            insert=false;
        }
        else if(giornoNascita.equals("-1")){
            System.out.println("giorno");
            insert=false;
        }
        else if(meseNascita.equals("-1")){
            System.out.println("mese");
            insert=false;
        }
        else if(annoNascita.equals("-1")){
            System.out.println("anno");
            insert=false;
        }
        else if(indirizzoResidenza.equals("")){
            System.out.println("indirizzo");
            insert=false;
        }
        else if(email.equals("")){
            System.out.println("email");
            insert=false;
        }
        else if(password.equals("")){
            System.out.println("password");
            insert=false;
        }
        else if(!password.equals(confPassword)){
            System.out.println("confPassword");
            insert=false;
        }
        StringBuffer hashedpasswd = null;
        boolean cripted = false;
        try {
            MessageDigest alg = MessageDigest.getInstance("MD5");
            alg.reset();
            alg.update(password.getBytes());
            byte[] digest = alg.digest();
            hashedpasswd = new StringBuffer();
            String hx;
            for (int i=0;i<digest.length;i++){
                hx =  Integer.toHexString(0xFF & digest[i]);
                //0x03 is equal to 0x3, but we need 0x03 for our md5sum
                if(hx.length() == 1){hx = "0" + hx;}
                hashedpasswd.append(hx);
                cripted = true;
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ServletRegistrazione.class.getName()).log(Level.SEVERE, null, ex);
        }
                
        String result = new String();
        if(insert && cripted){
            char s;
            if(sesso.equals("maschio")){
                s = 'M';
            }
            else{
                s = 'F';
            }
            String dataNascita = giornoNascita + "-" + meseNascita + "-" + annoNascita;
            result = businessLogic.insertUtente(codiceFiscale, nome, cognome, s, dataNascita, luogoNascita, indirizzoResidenza, email, hashedpasswd.toString(), telefono);
            
            if(result.equals("InserimentoEffettuato"))
            {
                session.setAttribute("checkInsertUtente", "inserimentoEffettuato");
            }
            else if(result.equals("ErroreDB"))
                session.setAttribute("checkInsertUtente", "errore");        
            else
                session.setAttribute("checkInsertUtente", "ErroreUtente");        
        }
        else{
            session.setAttribute("checkInsertUtente", "ErroreCredenziali");
        }               
        
        RequestDispatcher rdRegistrazione = getServletContext().getRequestDispatcher("/registrazione.jsp");
        rdRegistrazione.forward(request, response);    
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
